package com.why.pool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.why.enums.ErrorEnum;
import com.why.exception.RpcException;

import java.util.concurrent.*;

/**
 * @program: why-rpc-framework
 * @description:
 * @author: @why
 * @create: 2021-03-15 16:11
 **/
public class ThreadPoolFactroy {

    private static ExecutorService service;
    private static int CORE_POOL_SIZE = 6;
    private static int MAX_POOL_SIZE = 60;
    private static int KEEP_ALIVE_TIME = 60;
    private static int BLOCK_QUEUE_SIZE = 100;
    private static String THREAD_POOL_NAME = "worker";

    private ThreadPoolFactroy() {
    }

    public static ExecutorService getExecutorService(String threadPoolName) {
        if(threadPoolName!=null){
            THREAD_POOL_NAME=threadPoolName;
        }else {
            throw  new RpcException(ErrorEnum.ILLEGAL_NAME);
        }
        return getExecutorService();
    }

    public static ExecutorService getExecutorService() {

        ArrayBlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(BLOCK_QUEUE_SIZE);
        //定制线程池的名字
        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat(THREAD_POOL_NAME + "-%d").setDaemon(false).build();
        service = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, blockingQueue, factory);

        return service;
    }
}